package com.tim.shadow.lib.act.move;

import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

/*
 * Author: poper Email:xut@bluemobi.cn
 * Created Date:2013-4-16
 * Copyright @ 2013 BU
 * Description: 类描述
 *
 * History:
 */
public abstract class OnLongPressMove implements OnTouchListener {

	public final int DEFAULT_LONGPRESS_TIME = 1500;
	private int mLongPressTime = DEFAULT_LONGPRESS_TIME;

	private ILongPressMoveListener mLongPressMoveListener;
	private LongPressMoveEvent mLongPressMoveEvent;

	int pressNum = 0;
	/**
	 * 是否松开了手指
	 */
	boolean isUped = true;
	/**
	 * 是否移动超过距离
	 */
	boolean isMoveOver;

	/**
	 * 是否移动状态
	 */
	boolean isMovingStarted;

	int[] locationOnScreen = new int[2];
	View locationView;
	int mX, mY;

	@Override
	public boolean onTouch(View v, MotionEvent event) {

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			v.getLocationOnScreen(locationOnScreen);
			mLongPressMoveEvent = new LongPressMoveEvent(locationView,
					locationOnScreen[0], locationOnScreen[1],
					(int) event.getX(), (int) event.getY());

			locationView = v;
			isUped = false;
			isMoveOver = false;
			pressNum++;
			new Handler().postDelayed(moveRunnable, mLongPressTime);
			break;
		case MotionEvent.ACTION_UP:
			isUped = true;
			if (isMovingStarted) {
				mLongPressMoveEvent.setNowEvent((int) event.getX(),
						(int) event.getY());
				mLongPressMoveListener.onEndMove(mLongPressMoveEvent);
			}
			mLongPressMoveEvent = null;
			isMovingStarted = false;
			break;
		case MotionEvent.ACTION_MOVE:
			if (isMovingStarted) {
				mLongPressMoveEvent.setNowEvent((int) event.getX(),
						(int) event.getY());
				mLongPressMoveListener.onStartMove(mLongPressMoveEvent);
			}
			break;
		}
		return true;
	}

	private Runnable moveRunnable = new Runnable() {

		@Override
		public void run() {
			pressNum--;
			if (pressNum == 0 && !isMoveOver && isUped) {
				if (null != mLongPressMoveListener) {
					mLongPressMoveListener.onStartMove(mLongPressMoveEvent);
					isMovingStarted = true;
				}
			}
		}
	};

	public ILongPressMoveListener getmLongPressMoveListener() {
		return mLongPressMoveListener;
	}

	public void setmLongPressMoveListener(
			ILongPressMoveListener mLongPressMoveListener) {
		this.mLongPressMoveListener = mLongPressMoveListener;
	}

	abstract class ILongPressMoveListener {
		public abstract void onStartMove(LongPressMoveEvent event);

		public abstract void onMoving(LongPressMoveEvent event);

		public abstract void onEndMove(LongPressMoveEvent event);
	}

}
